import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/modules/address/addressList/controllers/address_list_controller.dart';
import 'package:xiaomi_shop/app/services/signService.dart';
import 'package:xiaomi_shop/app/services/userService.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/index.dart';

class AddressAddController extends GetxController {
  final TextEditingController nameEditController = TextEditingController();
  final TextEditingController phoneEditController = TextEditingController();
  final TextEditingController areaEditController = TextEditingController();
  final TextEditingController detailAreaEditController =
      TextEditingController();
  int type = Get.arguments["type"];
  String addressId = Get.arguments["id"];
  String locationCode = "110000";
  @override
  void onInit() {
    super.onInit();
    if (type == 1) {
      initAddressData();
    }
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  initAddressData() {
    nameEditController.text = Get.arguments["name"];
    phoneEditController.text = Get.arguments["phone"];

    String address = Get.arguments["address"];
    List addressList = address.split(" ");
    if (addressList.length > 3) {
      areaEditController.text =
          "${addressList[0]} ${addressList[1]} ${addressList[2]}";
      addressList.removeRange(0, 3);
      detailAreaEditController.text = addressList.join(" ");
    }
  }

  // 新增收货地址
  addAddress() async {
    if (nameEditController.text.isEmpty) {
      Toast.show("姓名不能为空");
      return;
    }
    if (phoneEditController.text.isEmpty) {
      Toast.show("电话不能为空");
      return;
    }
    if (areaEditController.text.isEmpty) {
      Toast.show("请选择收货地区");
      return;
    }
    if (detailAreaEditController.text.isEmpty) {
      Toast.show("请填写详细收货地址");
      return;
    }
    UserModel? user = await UserService.getUser();

    Map tempJson = {
      "uid": user?.id,
      "name": nameEditController.text,
      "phone": phoneEditController.text,
      "address": "${areaEditController.text} ${detailAreaEditController.text}",
    };
    if (type == 1) {
      tempJson["id"] = addressId;
    }
    // 获取签名
    String sign = SignService.sign({...tempJson, "salt": user?.salt});

    var response = await XHttp.getInstance().post(
        type == 1 ? Api.editAddress : Api.addAddress,
        {...tempJson, "sign": sign});
    if (response != null) {
      Result result = response as Result;
      if (result.data["success"]) {
        AddressListController listController =
            Get.find<AddressListController>();
        await listController.getAddressList();
        Get.back();
      } else {
        Toast.show(result.data["message"], type: Toast.ERROR);
      }
    } else {
      Toast.show("网络错误", type: Toast.ERROR);
    }
  }
}
